import { defineStore } from 'pinia'
import { ref, watch } from 'vue'
import type {
  FunType,
  HomeFun,
  HomeFunData,
  HomeFunPropertyData,
} from '../types/homeFun'
import { StorageKey } from '../utils/enum'
import default_config from '../config/default_config'
import { useResourcesStore } from './resources'
import { getNumber } from '../utils'
import { useLogStore } from './log'
import dayjs from 'dayjs'

export const useBuildingsStore = defineStore('buildings', () => {
  const homeFun = ref<HomeFunData>({})
  const homeFunProperty = ref<HomeFunPropertyData>({
    catchPower: 10,
  })
  const resourcesStore = useResourcesStore()
  const logStore = useLogStore()
  const buildingConfig = default_config.building

  // 初始化
  const initData = async () => {
    let _homeFunData

    try {
      const localRs = await localStorage.getItem(StorageKey.HOME_FUN_DATA)
      const localHomeFunProperty = await localStorage.getItem(
        StorageKey.HOME_FUN_PROPERTY_DATA
      )

      if (localRs) {
        _homeFunData = JSON.parse(localRs)
      } else {
        // @ts-ignore
        _homeFunData = default_config.homeFun
      }

      if (localHomeFunProperty) {
        homeFunProperty.value = JSON.parse(localHomeFunProperty)
      } else {
        // @ts-ignore
        homeFunProperty.value = default_config.homeFunProperty
      }

      homeFun.value = _homeFunData
    } catch (error) {
      console.error(error)
    }
  }

  // 事件触发
  const triggerEvent = (id: FunType, params?: any) => {
    switch (id) {
      case 'plantSeed':
        handlePlantSeed(params)
        break
      default:
        break
    }
  }

  const updateHomeFun = (id: FunType, key: string, value: any) => {
    if (!homeFun.value[id]) {
      return
    }
    // @ts-ignore
    homeFun.value[id][key] = value
  }

  /**
   * 播种 树果树
   * 消耗：种子
   * 效果：产树果
   * 拆除：返还种子
   */
  const handlePlantSeed = (params?: { split?: boolean }) => {
    const _item = resourcesStore.data.seeds
    const { split } = params ?? {}

    if (_item) {
      if (split) {
        updateHomeFun(
          'plantSeed',
          'number',
          getNumber(homeFun.value.plantSeed?.number) - 1
        )
        resourcesStore.updateData(
          'seeds',
          'details.value',
          getNumber(_item.details.value) + buildingConfig.plantSeed.returnSeeds
        )
        resourcesStore.updateHappyPoint(-1)
      } else {
        updateHomeFun(
          'plantSeed',
          'number',
          getNumber(homeFun.value.plantSeed?.number) + 1
        )
        resourcesStore.updateData(
          'seeds',
          'details.value',
          _item.details.value - buildingConfig.plantSeed.seeds
        )
        resourcesStore.updateData('crops', 'enabled', true)
        resourcesStore.updateHappyPoint(1)
      }

      if (getNumber(homeFun.value.plantSeed?.number) > 0) {
        updateHomeFun('plantSeed', 'useSplit', true)
      } else {
        updateHomeFun('plantSeed', 'useSplit', false)
      }
      resourcesStore.updateData(
        'crops',
        'details.rate',
        getNumber(_item.details.rate) +
          buildingConfig.plantSeed.treeFruit *
            getNumber(homeFun.value.plantSeed?.number)
      )
    }
  }

  // 监听种子数量变化
  watch(
    () => resourcesStore.data.seeds?.details.value,
    (newVal) => {
      if (!homeFun.value.plantSeed) {
        return
      }
      if ((!newVal && typeof newVal === 'object') || newVal === undefined) {
        return
      }
      if (newVal <= 0) {
        homeFun.value.plantSeed.disabled = true
        updateHomeFun('plantSeed', 'disabled', true)
      } else if (newVal >= 10) {
        updateHomeFun('plantSeed', 'disabled', false)
      }
    }
  )

  return {
    homeFun,
    initData,
    triggerEvent,
  }
})
